package com.wbu.estatemanagement.controller;

import com.wbu.estatemanagement.common.MessageConstant;
import com.wbu.estatemanagement.common.Result;
import com.wbu.estatemanagement.common.StatusCode;
import com.wbu.estatemanagement.domain.Admin;
import com.wbu.estatemanagement.domain.User;
import com.wbu.estatemanagement.service.AdminService;
import com.wbu.estatemanagement.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
import java.text.ParseException;

@RestController
@RequestMapping("login")
public class  LoginController {
    @Autowired
    AdminService adminService;
    @Autowired
    UserService userService;

    @PostMapping("/login")
    public ModelAndView index(){
        return new ModelAndView("/user_login.html");
    }

    @PostMapping("/admin")
    public Result admminLogin(@RequestBody Admin admin,HttpSession httpSession){
         admin=adminService.findByName(admin);

         if(admin!=null) {
             httpSession.setAttribute("admin",admin);
             return new Result(true, StatusCode.OK, MessageConstant.ADMIN_LOGIN_SUCCESS);
         }
             return new Result(false, StatusCode.ERROR, MessageConstant.ADMIN_LOGIN_FAIL);
    }

    @PostMapping("/user")
    public Result userLogin(@RequestBody User user,HttpSession httpSession) throws ParseException {
        user=userService.findOne(user);
        if(user!=null) {
            httpSession.setAttribute("user",user);

            return new Result(true, StatusCode.OK, MessageConstant.USER_LOGIN_SUCCESS,user);
        }
        return new Result(false, StatusCode.ERROR, MessageConstant.USER_LOGIN_FAIL);
    }
}
